package com.lsq.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @version 1.0
 * @author:罗苏琴
 * @Date 2024/11/25 15:35
 */
public class MyBatisUtil {
    static SqlSessionFactory sqlSessionFactory;
    static {
        try{
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    static SqlSession sqlSession;

    /**
     * 获取SqlSession
     */
    public static SqlSession getSqlSession(boolean autoCommit){
        return sqlSessionFactory.openSession(autoCommit);
    }
    /**
     * 获取Mapper代理类
     */
    public static <T> T getMapper(Class<T> clazz,boolean autoCommit){
        sqlSession=getSqlSession(autoCommit);
        return sqlSession.getMapper(clazz);
    }
    /**
     * 关闭会话
     */
    public static void closeSqlSession(){
        if(sqlSession!=null){
            sqlSession.close();
        }
    }
}
